package com.music.music.web;

import com.music.common.core.constant.Constants;
import com.music.common.core.constant.SecurityConstants;
import com.music.common.core.web.controller.BaseController;
import com.music.common.core.web.domain.AjaxResult;
import com.music.common.core.web.page.TableDataInfo;
import com.music.music.domain.Collect;
import com.music.music.domain.Music;
import com.music.music.service.CollectService;
import com.music.music.service.MusicService;
import com.music.music.vo.MusicVo;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户收藏Controller
 *
 * @author ruoyi
 * @date 2024-10-22
 */
@RestController
@RequestMapping("/collect/web")
public class CollectWebController extends BaseController {
    @Resource
    private CollectService collectService;
    @Resource
    private MusicService musicService;

    /**
     * 查询用户收藏列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Collect collect) {
        startPage();
        List<MusicVo> list = collectService.selectCollectListVo(collect);
        return getDataTable(list);
    }

    /**
     * 新增用户收藏
     */
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody Collect collect) {
        List<Collect> list = collectService.selectCollectList(collect);
        if (list.isEmpty()) {
            // 收藏数+1
            musicService.updateMusicCollectCount(new Music(collect.getCollectMusicId(), Constants.ADD_MUSIC_COLLECT_COUNT));
            // 收藏表插入数据
            return toAjax(collectService.insertCollect(collect));
        }
        return AjaxResult.error();
    }

    /**
     * 删除用户收藏
     */
    @DeleteMapping("/{collectMusicIds}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] collectMusicIds, HttpServletRequest request) {
        Long userId = Long.parseLong(request.getHeader(SecurityConstants.DETAILS_USER_ID));
        System.out.println("userId = " + userId);
        // 收藏数-1
        musicService.updateMusicsCollectCount(collectMusicIds, Constants.DEL_MUSIC_COLLECT_COUNT);
        // 收藏表删除数据
        return toAjax(collectService.deleteCollectByCollectMusicIds(userId, collectMusicIds));
    }
}
